package com.lcifn.stream;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;

import org.junit.Test;

public class StockTest {

	List<Stock> stockList = new ArrayList<>();
	
	@Test
	public void testStock(){
		/* 1.从大集合中获取小集合 */
		
		// 获取id的集合
		List<Long> idList = stockList.stream().map(Stock::getId).collect(Collectors.toList());
		// 获取skuid集合并去重
		List<Long> skuIdList = stockList.stream().map(Stock::getSkuId).distinct().collect(Collectors.toList());
		// 获取supplierId集合(supplierId的类型为int，返回List<Integer>,使用boxed方法装箱)
		Set<Integer> supplierIdSet = stockList.stream().mapToInt(Stock::getSupplierId).boxed().collect(Collectors.toSet());
		
		/* 2.分组与分片 */
		// 按skuid分组
		Map<Long, List<Stock>> skuIdStockMap = stockList.stream().collect(Collectors.groupingBy(Stock::getSkuId));
		// 过滤supplierId=1然后按skuId分组
		Map<Long, List<Stock>> filterSkuIdStockMap = stockList.stream().filter(s -> s.getSupplierId() == 1).collect(Collectors.groupingBy(Stock::getSkuId));
		// 按状态分为不可用和其他两个分片
		Map<Boolean, List<Stock>> partitionStockMap = stockList.stream().collect(Collectors.partitioningBy(s -> s.getStatus() == 0));
		
		/* 3.计数与求和 */
		// 统计skuId=1的记录数
		long skuIdRecordNum = stockList.stream().filter(s -> s.getSkuId() == 1).count();
		// 统计skuId=1的总库存量
		BigDecimal skuIdAmountSum = stockList.stream().filter(s -> s.getSkuId() == 1).map(Stock::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
		
		/* 4.特定用法 */
		
		// 多重分组并排序，先按supplierId分组，再按skuId分组，排序规则，先supplierId后skuId
		Map<Integer, Map<Long, List<Stock>>> supplierSkuStockMap = stockList.stream().collect(Collectors.groupingBy(Stock::getSupplierId, TreeMap::new,
				Collectors.groupingBy(Stock::getSkuId, TreeMap::new, Collectors.toList())));
		
		// 多条件排序，先按supplierId正序排，再按skuId倒序排
		// (非stream方法，而是集合的sort方法，直接改变原集合元素，使用Function参数)
		stockList.sort(Comparator.comparing(Stock::getSupplierId)
				.thenComparing(Stock::getSkuId, Comparator.reverseOrder()));
		
	}
}
